//
//  Album.m
//  我自己做的相册
//
//  Created by dllo on 16/3/19.
//  Copyright © 2016年 Apon. All rights reserved.
//

#import "Album.h"
#import "MyScrollView.h"
@interface Album()<UIScrollViewDelegate>

@property(nonatomic, retain) UIPageControl *pag;
@property(nonatomic, retain) MyScrollView *scroll;

@end




@implementation Album



- (instancetype)initWithFrame:(CGRect)frame withImages:(NSArray<UIImage *> *)images{
    self = [super initWithFrame:frame];
    if (self) {
        [self configWithFrame:frame withImages:images];
    }
    
    return self;
}


- (void)configWithFrame:(CGRect)frame withImages:(NSArray<UIImage *> *)images{
    //创建scoll对象
    self.scroll = [[MyScrollView alloc]initWithFrame:self.bounds withImages:images delegate:self];
    [self addSubview:self.scroll];
    //指定代理人
    self.scroll.delegate = self;
    
    //创建page对象
    self.pag = [[UIPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 80, frame.size.width, 40)];
    [self addSubview:self.pag];
    //页数
    self.pag.numberOfPages = images.count;
    //添加事件
    [self.pag addTarget:self action:@selector(handlePag) forControlEvents:UIControlEventValueChanged];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // page跟随scoll滚动而改变
    self.pag.currentPage = scrollView.contentOffset.x / self.bounds.size.width;
    
    // 判断滑动的scrollView是大ScrollView时
    if (scrollView == self.scroll) {
        
        for (UIScrollView *scrollOfSmall in self.scroll.subviews) {
            
            if ([scrollOfSmall.class isSubclassOfClass:[UIScrollView class]]) {
                
                scrollOfSmall.zoomScale = 1;
            }
            
        }
        if (self.scroll.contentOffset.x == 0) {
            scrollView.contentOffset = CGPointMake(self.scroll.contentSize.width - self.scroll.frame.size.width , 0);
        }
        else if (self.scroll.contentOffset.x == (self.scroll.contentSize.width - self.scroll.frame.size.width)){
            scrollView.contentOffset = CGPointMake(0, 0);
            
        }
    }
    
}
//** 返回需要缩放的视图. */
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    // 判断是小scrollView
    if (scrollView != self.scroll) {
        
        //NSLog(@"%@", scrollView);
        return [scrollView.subviews firstObject];
        
    } else {
        
        return nil;
    }
    
}

- (void)handlePag{
    //滚动
    [self.scroll setContentOffset:CGPointMake(self.frame.size.width * self.pag.currentPage, 0) animated:YES];
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
